<?php
//部门
namespace app\crm\controller;

use app\crm\model\Sys;
use think\Config;
use think\Request;
use think\Exception;
use app\crm\model\Department as DepartmentModel;
use app\crm\model\Staff as StaffModel;
class Department extends \CrmController
{
    static private $DiDuiBumen = [];
    /**
     * 部门列表接口
     */
    public function all()
    {
        try {
            $this->successTerminate($this->_all());
        } catch(Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
        return null;
    }

    protected function _all($flush = false)
    {
        return $this->cacheFirst(\CacheKey::DEPART_ALL, function() {
            $all =  DepartmentModel::all(function ($query) {
                /* @var $query Query */
                $query
                    ->field('department_id, department_name, parent_id')
                    ->where('is_delete', 0);

            });
            return $this->tree($all, 0);
        }, $flush);
    }

    /**
     * 允许限制级数
     * @param $categories
     * @param int $pid
     * @param int $levelLimit
     * @param int $level
     * @return array
     */
    private function tree($categories, $pid = 0, $levelLimit = 0, $level = 1)
    {
        $children = [];
        foreach ($categories as $category) {
            if ($category['parent_id'] === $pid) {

                if ($levelLimit === 0 || $level < $levelLimit) {
                    $category['is_show'] = false;
                    $category['children'] = $this->tree($categories, $category['department_id'], $levelLimit, $level + 1);
                }

                $children[] = $category;
            }
        }
        return $children;
    }
    /**
     * 部门新增接口
     */
    public function save(Request $request){
        $params = delToken($request->param());
        try {
            $weixinList = $this->qiyeweixin->DepartmentList();
            //判断部门是否是已存在
            $is = 0;
            foreach ($weixinList as $k=>$v){
                if($params['department_name'] == $v->name&&$params['parent_id'] ==$v->parentid)$is++;
            }
            if($is>0){
                $this->serverErrorTerminate('部门名字已存在！');
            }else{

                $departmentData =  new \weworkapi\api\datastructure\Department();
                {
                    $departmentData->name = $params['department_name'];
                    $departmentData->parentid = intval($params['parent_id']);
                }
                $params['department_id'] = $this->qiyeweixin->DepartmentCreate($departmentData);

                $Department = new DepartmentModel();
                $Department->data($params)->allowField(true)->save();
                $data = ['id'=>$Department->department_id];
                $this->successTerminate($data);
            }
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     * 部门重命名接口
     */

    public function update(Request $request){
        $params = delToken($request->param());
        try {
            $departmentData =  new \weworkapi\api\datastructure\Department();
            {
                $departmentData->name = $params['department_name'];
                $departmentData->id =  intval($params['department_id']);
            }

            $this->qiyeweixin->DepartmentUpdate($departmentData);
            $Department = new DepartmentModel();
            $pk = $Department->getPk();
            $uop['department_name'] = $params['department_name'];
            $Department->allowField(true)->save($uop,[$pk=>$params['department_id']]);
            $data = ['name'=>$Department->department_name];
            $this->successTerminate($data);
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     * 部门删除接口
     */

    public function delete(Request $request){
        $params = delToken($request->param());
        try {
            $Department = new DepartmentModel();
            $pk = $Department->getPk();
            $isR = $this->getStaffCount($params['department_id']);
            if($isR>0){
                $this->serverErrorTerminate('本门下有员工，不允许删除');
            }else{
                $this->qiyeweixin->DepartmentDelete(intval($params['department_id']));
                $Department->allowField(true)->where($pk,$params['department_id'])->delete();
                $this->successTerminate();
            }

        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     * 查询部门下员工人数
     */
    public function getStaffCount($department_id){
        $number = 0;
        $StaffModel = new StaffModel();
        $StaffDb = $StaffModel->StaffDb();
        $departmentData = $this->getDepartmentAffiliate($department_id);
        foreach ($departmentData as $k =>$v){
            $number += $StaffDb->where('department_id',$v['department_id'])->count();
        }
        return $number;
    }
    /**
     * 查询部门下所有子部门 返回该部门下所有部门
     */
    public function getDepartmentAffiliate($department_id,$sqlData=false){

        $DepartmentModel = new DepartmentModel();
        $DepartmentDb = $DepartmentModel->DepartmentDb();
        $DepartmentData = $DepartmentDb->where('is_delete',0)->select();
        foreach ($DepartmentData as $DepartmentK=>$DepartmentV){
            if($department_id==$DepartmentV['department_id']){
                static::$DiDuiBumen[] = $DepartmentV;
            }
        }
        $this->DiGuiDep($DepartmentData,$department_id);
        if ($sqlData){
            $retData = [];
            $sqlS = static::$DiDuiBumen;
            foreach ($sqlS as $v){
                $retData[] =  $v['department_id'];
            }

            return $retData;
        }
        return static::$DiDuiBumen;

    }
    //递归部门
    private function DiGuiDep($DepartmentData,$department_id){
        foreach ($DepartmentData as $DepartmentK=>$DepartmentV){
            if($department_id==$DepartmentV['parent_id']){
                static::$DiDuiBumen[] = $DepartmentV;
                $this->DiGuiDep($DepartmentData,$DepartmentV['department_id']);
            }
        }
    }
    /**
     * 修改部门管理人接口
     */
    public function custodian(Request $request){
        $params = delToken($request->param());
        try {
            $DepartmentModel = new DepartmentModel();
            $pk = $DepartmentModel->getPk();
            $DepartmentDb = $DepartmentModel->DepartmentDb();
            $DepartmentDb->where($pk,$params['department_id'])->update(['staff_id'=>$params['staff_id']]);
            $this->successTerminate();
        } catch (Exception $e) {
            $this->serverErrorTerminate($e->getMessage());
        }
    }
    /**
     *微信同步
     */
    public function synchronization(){
        //获取微信所有本门
        $DepartmentList = $this->qiyeweixin->DepartmentList();
        $is_xx = 0;
        $did = 0;
        foreach ($DepartmentList as $list2){
            if($list2->name=='上下游互动'){
                $is_xx++;
                $did = $list2->id;
            }
        }
        $departmentData =  new \weworkapi\api\datastructure\Department();
        if($did==0){
            $departmentData->parentid = 1;
            $departmentData->name = '上下游互动';
            $this->qiyeweixin->DepartmentCreate($departmentData);
        }
        foreach ($DepartmentList as $list3){
            if($list3->name=='上下游互动'){

                $did = $list3->id;
            }
        }
        $DepartmentList = $this->qiyeweixin->DepartmentList();
        $SYS = new Sys();
        $SYS->where('id',1)->update(['crm_sxyhd_did'=>$did]);

        $addDatas = [];
        $Department = new \app\crm\model\Department();
        $DepartmentDb = $Department->DepartmentDb();
        $pcDepartment = $DepartmentDb->column('department_id,parent_id,department_name','department_id');
        //修改
        foreach ($DepartmentList as $k=>$v){
            if (array_key_exists($v->id,$pcDepartment))
            {
                $up['department_name'] = $v->name;
                $up['parent_id'] = $v->parentid;
                $Department->where('department_id',$v->id)->update($up);
                unset($pcDepartment[$v->id]);
            }
            else
            {
                $addDatas[] = $v;
            }

        }

        //pc新增
        if(count($addDatas)>0){

            foreach ($addDatas as $k1=>$v1){
                if($v1->name!='上下游互动'){
                    $add['department_name'] = $v1->name;
                    $add['parent_id'] = $v1->parentid;
                    $add['department_id'] = $v1->id;
                    $Department->insert($add);
                }else{

                    //判断是否有上下游互动部门
                    $is_xx++;
                }
            }
        }
        //wx新增
        if(count($pcDepartment)>0){
            $departmentData =  new \weworkapi\api\datastructure\Department();
            foreach ($pcDepartment as $k2=>$v2){
                {
                    $departmentData->id = $v2['department_id'];
                    $departmentData->name =  $v2['department_name'];
                    $departmentData->parentid =  $v2['parent_id'];
                }
                $this->qiyeweixin->DepartmentCreate($departmentData);
            }

        }


    }

    public function a1(){
       $a = Config::get('sxyhd');
       p($a);
    }

    public function allDep(){
        $all =  DepartmentModel::all(function ($query) {
            /* @var $query Query */
            $query
                ->field('department_id, department_name')
                ->where('is_delete', 0);
        });

        $this->successTerminate($all);

    }

}   
